package org.linlinjava.litemall.wx.web;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wx/cart")
public class WxCartController {
    private final Log logger = LogFactory.getLog(WxCartController.class);

    private LitemallCartService cartService;

    private LitemallGoodsService goodsService;

    private LitemallProductService productService;

    private LitemallAddressService addressService;

    private LitemallFreightService freightService;

    private LitemallRegionService regionService;

    public WxCartController(
        LitemallCartService cartService,
        LitemallGoodsService goodsService,
        LitemallProductService productService,
        LitemallAddressService addressService,
        LitemallFreightService freightService,
        LitemallRegionService regionService) {
        this.cartService = cartService;
        this.goodsService = goodsService;
        this.productService = productService;
        this.addressService = addressService;
        this.freightService = freightService;
        this.regionService = regionService;
    }

    /**
     * 购物车
     *
     * @param userId 用户ID
     * @return 购物车
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data:
     *          {
     *              cartList: xxx,
     *              cartTotal: xxx
     *          }
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @GetMapping("index")
    public Object index(@LoginUser Integer userId) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }

        List<LitemallCart> cartList = cartService.queryByUid(userId);
        int goodsCount = 0;    //默认的商品数量
        int intergral = 0;    //默认的积分总和
        int irintergral = 0;  //赠送的积分
        BigDecimal goodsAmount = new BigDecimal(0.00);   //默认的爱币总和
        BigDecimal irgoodsAmount = new BigDecimal(0.00); //赠送的爱币总和
        Integer checkedGoodsCount = 0;    //选中后的商品总和
        int checkedIntergral = 0;     //选中后的积分总和
        int ircheckedIntergral = 0;     //赠送的选中后的积分总和
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);  //选中后的爱币总和
        BigDecimal ircheckedGoodsAmount = new BigDecimal(0.00);  //赠送选中后的爱币总和
        for (LitemallCart cart : cartList) {
            goodsCount += cart.getNumber();
            //默认的积分计算
            if( cart.getIntegralFlag()==1){   //判断是消费还是赠送
                intergral = intergral+(cart.getIntegral()*cart.getNumber());
            }else if(cart.getIntegralFlag()!=null && cart.getIntegralFlag()!=1){
                irintergral = irintergral+(cart.getIntegral()*cart.getNumber());
            }else {
                System.err.print("积分列表为空");
            }
            //默认的爱币计算
            if(cart.getPriceFlag()==1){
                goodsAmount = goodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }else if(cart.getPriceFlag()!=null && cart.getPriceFlag()!=1){
                irgoodsAmount = irgoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }else {
                System.err.print("爱币列表为空");
            }

            if (cart.getChecked()) {
                checkedGoodsCount += cart.getNumber();
                //选中的积分计算 判断是消费还是赠送
                if(cart.getIntegralFlag()==1){
                    checkedIntergral = checkedIntergral+(cart.getIntegral()*cart.getNumber());
                }else if(cart.getIntegralFlag()!=null && cart.getIntegralFlag()!=1){
                    ircheckedIntergral = ircheckedIntergral+(cart.getIntegral()*cart.getNumber());
                }else {
                    System.err.print("选中的积分列表为空");
                }

                //选中的爱币计算
                if(cart.getPriceFlag()==1){
                    checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
                }else if(cart.getPriceFlag()!=null && cart.getPriceFlag()!=1){
                    ircheckedGoodsAmount = ircheckedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
                }else{
                    System.err.print("选中的爱币列表为空");
                }
            }
        }

        Map<String, Object> cartTotal = new HashMap<>(8);
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("intergral",intergral);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("irintergral",irintergral);
        cartTotal.put("irgoodsAmount",irgoodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedIntergral",checkedIntergral);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);
        cartTotal.put("ircheckedIntergral",ircheckedIntergral);
        cartTotal.put("ircheckedGoodsAmount",ircheckedGoodsAmount);

        Map<String, Object> result = new HashMap<>(2);
        result.put("cartList", cartList);
        result.put("cartTotal", cartTotal);

        return ResponseUtil.ok(result);
    }

    /**
     * 添加商品加入购物车
     * 如果已经存在购物车货品，则添加数量；
     * 否则添加新的购物车货品项。
     *
     * @param userId 用户ID
     * @param cart 购物车商品信息， { goodsId: xxx, productId: xxx, number: xxx }
     * @return 加入购物车操作结果
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("add")
    public Object add(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
        System.err.println(cart);
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        if(cart == null){
            return ResponseUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if(!ObjectUtils.allNotNull(productId, number, goodsId)){
            return ResponseUtil.badArgument();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(400, "商品已下架");
        }

        LitemallProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
        if(existCart == null){
            //取得规格的信息,判断规格库存
            if(product == null || number > product.getNumber() ){
                return ResponseUtil.fail(400, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(product.getPrice());
            cart.setIntegral(product.getIntegral());
            cart.setPriceFlag(product.getPriceFlag());
            cart.setIntegralFlag(product.getIntegralFlag());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        }
        else{
            //取得规格的信息,判断规格库存
            int num = existCart.getNumber() + number;
            if(num >  product.getNumber()){
                return ResponseUtil.fail(400, "库存不足");
            }
            existCart.setNumber((short)num);
            cartService.update(existCart);
        }

        return goodscount(userId);
    }

    /**
     * 立即购买商品
     *
     * 和 前面一个方法add的区别在于
     * 1. 如果购物车内已经存在购物车货品，前者的逻辑是数量添加，这里的逻辑是数量覆盖
     * 2. 添加成功以后，前者的逻辑是返回当前购物车商品数量，这里的逻辑是返回对应购物车项的ID
     *
     * @param userId 用户ID
     * @param cart 购物车商品信息， { goodsId: xxx, productId: xxx, number: xxx }
     * @return 即购买操作结果
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("fastadd")
    public Object fastadd(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        if(cart == null){
            return ResponseUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if(!ObjectUtils.allNotNull(productId, number, goodsId)){
            return ResponseUtil.badArgument();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(400, "商品已下架");
        }

        LitemallProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
        if(existCart == null){
            //取得规格的信息,判断规格库存
            if(product == null || number > product.getNumber() ){
                return ResponseUtil.fail(400, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(product.getPrice());
            cart.setIntegral(product.getIntegral());
            cart.setIntegralFlag(product.getIntegralFlag());
            cart.setPriceFlag(product.getPriceFlag());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        }
        else{
            //取得规格的信息,判断规格库存
            int num = number;
            if(num >  product.getNumber()){
                return ResponseUtil.fail(400, "库存不足");
            }
            existCart.setNumber((short)num);
            cartService.update(existCart);
        }

        return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
    }

    /**
     * 更新指定的购物车信息
     * 目前只支持修改商品的数量
     *
     * @param userId 用户ID
     * @param cart 购物车商品信息， { id: xxx, goodsId: xxx, productId: xxx, number: xxx }
     * @return 更新购物车操作结果
     *   成功则 { errno: 0, errmsg: '成功' }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("update")
    public Object update(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        if(cart == null){
            return ResponseUtil.badArgument();
        }
        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        Integer id = cart.getId();
        if(!ObjectUtils.allNotNull(id, productId, number, goodsId)){
            return ResponseUtil.badArgument();
        }

        //判断是否存在该订单
        // 如果不存在，直接返回错误
        LitemallCart existCart = cartService.findById(id);
        if(existCart == null){
            return ResponseUtil.badArgumentValue();
        }

        // 判断goodsId和productId是否与当前cart里的值一致
        if(!existCart.getGoodsId().equals(goodsId)){
            return ResponseUtil.badArgumentValue();
        }
        if(!existCart.getProductId().equals(productId)){
            return ResponseUtil.badArgumentValue();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(403, "商品已下架");
        }

        //取得规格的信息,判断规格库存
        LitemallProduct product = productService.findById(productId);
        if(product == null || product.getNumber() < number){
            return ResponseUtil.fail(403, "库存不足");
        }

        existCart.setNumber(number.shortValue());
        cartService.update(existCart);
        return ResponseUtil.ok();
    }


    /**
     * 购物车商品勾选
     * 如果原来没有勾选，则设置勾选状态；如果商品已经勾选，则设置非勾选状态。
     *
     * @param userId 用户ID
     * @param body 购物车商品信息， { productIds: xxx }
     * @return 购物车信息
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("checked")
    public Object checked(@LoginUser Integer userId, @RequestBody String body) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        if(body == null){
            return ResponseUtil.badArgument();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");
        if(productIds == null){
            return ResponseUtil.badArgument();
        }

        Integer checkValue = JacksonUtil.parseInteger(body, "isChecked");
        if(checkValue == null){
            return ResponseUtil.badArgument();
        }
        boolean isChecked = (checkValue == 1);

        cartService.updateCheck(userId, productIds, isChecked);
        return index(userId);
    }

    /**
     * 购物车商品删除
     *
     * @param userId 用户ID
     * @param body 购物车商品信息， { productIds: xxx }
     * @return 购物车信息
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId, @RequestBody String body) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        if(body == null){
            return ResponseUtil.badArgument();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");

        if(productIds == null || productIds.size() == 0){
            return ResponseUtil.badArgument();
        }

        cartService.delete(productIds, userId);
        return index(userId);
    }

    /**
     * 购物车商品数量
     * 如果用户没有登录，则返回空数据。
     *
     * @param userId 用户ID
     * @return 购物车商品数量
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @RequestMapping("goodscount")
    public Object goodscount(@LoginUser Integer userId) {
        if(userId == null){
            return ResponseUtil.ok(0);
        }

        int goodsCount = 0;
        List<LitemallCart> cartList = cartService.queryByUid(userId);
        for(LitemallCart cart : cartList){
            goodsCount += cart.getNumber();
        }

        return ResponseUtil.ok(goodsCount);
    }

    @GetMapping("check")
    public Object check(@LoginUser Integer userId,String productIds){
        if(userId==null){
            return ResponseUtil.unlogin();
        }
        List<Integer> ids= Arrays.stream(productIds.split(",")).map(s->Integer.parseInt(s.trim())).collect(Collectors.toList());
        List<LitemallProduct> products1 = productService.queryByIds(ids);
        Map<String, Object> data = new HashMap<>(16);
        data.put("products",products1);
        return ResponseUtil.ok(data);
    }
    /**
     * 购物车下单信息
     *
     * @param userId 用户ID
     * @param cartId 购物车商品ID
     *    如果购物车商品ID是空，则下单当前用户所有购物车商品；
     *    如果购物车商品ID非空，则只下单当前购物车商品。
     * @param addressId 收货地址ID
     *    如果收货地址ID是空，则查询当前用户的默认地址。
     * @param couponId 优惠券ID
     *    目前不支持
     * @return 购物车下单信息
     *   成功则
     *  {
     *      errno: 0,
     *      errmsg: '成功',
     *      data:
     *      {
     *          addressId: xxx,
     *          checkedAddress: xxx,
     *          couponId: xxx,
     *          checkedCoupon: xxx,
     *          goodsTotalPrice: xxx,
     *          freightPrice: xxx,
     *          couponPrice: xxx,
     *          orderTotalPrice: xxx,
     *          actualPrice: xxx,
     *          checkedGoodsList: xxx
     *      }
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @GetMapping("checkout")
    public Object checkout(@LoginUser Integer userId, Integer cartId, Integer addressId, Integer couponId) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }

        // 收货地址
        LitemallAddress checkedAddress ;
        if(addressId == null || addressId.equals(0)){
            boolean mtype = false;
            checkedAddress = addressService.findDefault(userId,mtype);

            // 如果仍然没有地址，则是没有收获地址
            // 返回一个空的地址id=0，这样前端则会提醒添加地址
            if(checkedAddress == null){
                checkedAddress = new LitemallAddress();
                checkedAddress.setId(0);
                addressId = 0;
            }
            else{
                addressId = checkedAddress.getId();
            }

        }
        else {
            checkedAddress = addressService.findById(addressId);
            // 如果null, 则报错
            if(checkedAddress == null){
                return ResponseUtil.badArgumentValue();
            }
        }


        Map<String, Object> data = new HashMap<>(16);
        data.put("addressId", addressId);
        data.put("checkedAddress", checkedAddress);
        data.put("couponId", couponId);
        data.put("checkedCoupon", 0);
        data.put("couponList", "");
        data.put("goodsTotalPrice", "");
        data.put("couponPrice", "");
        data.put("orderTotalPrice", "");
        data.put("actualPrice", "");
        data.put("checkedGoodsList", 0);
        //扣除爱能积分和爱币  赠送爱能积分和爱币
        data.put("deductIntegral", 0);
        data.put("deductPrice", 0);
        data.put("giveIntegral",0);
        data.put("givePrice", 0);

        return ResponseUtil.ok(data);
    }

    /**
     * 商品优惠券列表
     * 目前不支持
     *
     * @param userId 用户ID
     * @return 商品优惠券信息
     *   成功则
     *  {
     *      errno: 0,f
     *      errmsg: '成功',
     *      data: xxx
     *  }
     *   失败则 { errno: XXX, errmsg: XXX }
     */
    @GetMapping("checkedCouponList")
    public Object checkedCouponList(@LoginUser Integer userId) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.unsupport();
    }

    /**
     * 计算运费
     *
     * @param userId 用户ID
     * @param body   订单信息，{ addressId: xxx }
     * @return 订单操作结果
     * 成功则 { errno: 0, errmsg: '成功', data: { freightPrice: xxx, } }
     * 失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("checkfreight")
    public Object checkfreight(@LoginUser Integer userId, @RequestBody String body) throws Exception {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (body == null) {
            return ResponseUtil.badArgument();
        }

        String addressIdStr = JacksonUtil.parseString(body, "addressId");
        Integer addressId = Integer.parseInt(addressIdStr);

        List<LitemallAddress> litemallAddressList = null;

        if (addressId == null || "0".equals(addressId.toString())) {
            Boolean mtype=false;
            litemallAddressList = addressService.queryByUid(userId,mtype);
            if(litemallAddressList != null){
                for(int i=0;i<litemallAddressList.size();i++){
                    if(litemallAddressList.get(i).getIsDefault()){
                        addressId = litemallAddressList.get(i).getId();
                    }
                }
            }
            else{
                return ResponseUtil.badArgument();
            }
        }

        //商品list
        String checkedGoodsStr =  JacksonUtil.parseString(body, "checkedGoodsList");

        List<String> checkedGoodsList = java.util.Arrays.asList(checkedGoodsStr.substring(1,checkedGoodsStr.length()-1).split("},"));

        if (checkedGoodsList.size() == 0) {
            return ResponseUtil.badArgumentValue();
        }

        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);//商品总售价

        Integer actualIntegral = 0;//商品总积分

        int goodsTotalWeight = 0;//订单全部商品重量，单位为g

        int specialtyGoodsWeight = 0;//订单特殊商品重量，单位为g

        int goodsWeight = 0;//订单非特殊商品重量，单位为g

        Boolean deleted ;

        LitemallProduct litemallProduct;

        //计算积分和爱币的数量
        for (int i = 0;i<checkedGoodsList.size();i++) {
            String checkedGoods = checkedGoodsList.get(i)+"}";
            Integer id = JacksonUtil.parseInteger(checkedGoods, "id");
            Boolean checked = JacksonUtil.parseBoolean(checkedGoods, "checked");
            deleted = goodsService.selectById(id);
            if(!deleted){
                if(checked){
                    String integralFlag = JacksonUtil.parseString(checkedGoods, "integralFlag");
                    String priceFlag = JacksonUtil.parseString(checkedGoods, "priceFlag");
                    Integer integral = JacksonUtil.parseInteger(checkedGoods, "integral");
                    Integer retailPrice = JacksonUtil.parseInteger(checkedGoods, "retailPrice");
                    Integer number = JacksonUtil.parseInteger(checkedGoods, "number");
                    int weight = 0;//商品重量，单位为g
                    Boolean specialtyGoods = false;//是否特殊商品
                    Integer productId = JacksonUtil.parseInteger(checkedGoods, "productId");
                    litemallProduct = productService.findById(productId);
                    if(litemallProduct != null && litemallProduct.getWeight()!=null){
                        weight = litemallProduct.getWeight();
                        specialtyGoods = litemallProduct.getSpecialtyGoods();
                    }
                    BigDecimal price = new BigDecimal(retailPrice.toString());
                    if(specialtyGoods == null || "".equals(specialtyGoods)){specialtyGoods = false;}
                    //如果订单中有特殊商品，则订单特殊商品重量相加
                    if(specialtyGoods){
                        specialtyGoodsWeight += weight*number;
                    }
                    //如果订单中有特殊商品，则订单非特殊商品重量相加
                    else{
                        goodsWeight += weight*number;
                    }

                    //订单全部商品重量相加
                    goodsTotalWeight += weight*number;

                    if ("1".equals(integralFlag)) {
                        actualIntegral += integral * number;
                    }

                    if ("1".equals(priceFlag)) {
                        checkedGoodsPrice = checkedGoodsPrice.add(price.multiply(new BigDecimal(number)));
                    }
                }
            }
        }


        /*计算收货地址运费标准开始*/
        //运费
        BigDecimal freightPrice = new BigDecimal(0.00);

        if(addressId != null && !"0".equals(addressId.toString())){
            LitemallAddress checkedAddress = addressService.findById(addressId);//根据收货地址查询省级code和市级code

            LitemallRegion litemallRegion = null;

            String provinceName = "";//收货地址的省级地区名称

            Integer freightCode = null;//取收货地址的省级code或者市级code

            int startingPrice = 0;//收货地址所在地区的起步价（重量少于3kg所需运费）

            int overWeightPrice = 0;//收货地址所在地区的超重价（超过3kg的部分每kg所需运费）

            //根据地区id查询
            litemallRegion = regionService.findById(checkedAddress.getProvinceId());

            if(litemallRegion != null){
                provinceName = litemallRegion.getName();
            }

            //判断收货地址是否是内蒙古自治区
            if("内蒙古自治区".equals(provinceName)){
                freightCode = checkedAddress.getCityId();//如果收货地址的省份是内蒙古自治区，取收货地址的市级code
            }
            else{
                freightCode = checkedAddress.getProvinceId();//如果收货地址的省份不是内蒙古自治区，取收货地址的省级code
            }

            LitemallFreight litemallFreight = null;

            if(freightCode != null){
                litemallFreight = freightService.selectByCode(freightCode);
                startingPrice = litemallFreight.getStartingPrice();//得到收货地址所在地区的起步价(3kg以内)
                overWeightPrice = litemallFreight.getOverWeightPrice();//得到收货地址所在地区的超重价(每kg)
            }
            /*计算收货地址运费标准结束*/

            /*新疆地区收费方式 将总积分和爱币换算成积分，每1000积分支付40爱币运费*/
            if("新疆维吾尔自治区".equals(provinceName)){
               //开始计算
                if(checkedGoodsPrice.compareTo(new BigDecimal(0))==1){
                    Integer aibi  = checkedGoodsPrice.setScale( 0, BigDecimal.ROUND_UP ).intValue();
                    actualIntegral = actualIntegral+aibi*5;
                    double num =  Math.ceil((double)actualIntegral/1000);
                    //最终的快递费
                    BigDecimal kuaiDiFei = new BigDecimal(Double.toString(num)).multiply(new BigDecimal(40));
                    freightPrice = kuaiDiFei;
                }else{
                    freightPrice = new BigDecimal(Double.toString(Math.ceil((double)actualIntegral/1000))).multiply(new BigDecimal(40));
                }
            }else {


                /*计算订单总运费开始*/
                double freightDecimal = 0.0;//运费保留小数点的价格
                //订单中有特殊商品
                if (specialtyGoodsWeight > 0) {
                    //如果订单总价不满足600积分或者88爱币，这里不需要考虑特殊商品和非特殊商品单独的重量
                    if (actualIntegral < 600 && checkedGoodsPrice.compareTo(new BigDecimal(88)) == -1) {
                        if (goodsTotalWeight > 0) {
                            freightPrice = freightPrice.add(new BigDecimal(startingPrice));
                        }
                        //如果全部商品的重量超过3000g
                        if (goodsTotalWeight > 3000) {
                            freightDecimal = overweightRate(goodsTotalWeight, overWeightPrice);//计算全部商品超重价
                            freightPrice = freightPrice.add(new BigDecimal(freightDecimal));
                        }
                    }
                    //如果订单总价满足600积分或者88爱币，这里需要考虑非特殊商品的重量
                    else {
                        //如果全是特殊商品和如果不全是特殊商品一样计算
                        if (specialtyGoodsWeight > 0) {
                            freightPrice = freightPrice.add(new BigDecimal(startingPrice));
                        }
                        //如果特殊商品的重量超过3000g
                        if (specialtyGoodsWeight > 3000) {
                            freightDecimal = overweightRate(specialtyGoodsWeight, overWeightPrice);//计算全部商品超重价
                            freightPrice = freightPrice.add(new BigDecimal(freightDecimal));
                        }
                    }
                }
                //订单中没有特殊商品，不作判断
                else {
                    //如果订单总价不满足600积分或者88爱币
                    if (actualIntegral > 600 || checkedGoodsPrice.compareTo(new BigDecimal(88)) == 1) {

                    }else{
                        if (goodsWeight > 0) {
                            freightPrice = freightPrice.add(new BigDecimal(startingPrice));
                        }
                        if (goodsWeight > 3000) {
                            freightDecimal = new BigDecimal((float)(goodsWeight - 3000) / 1000).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue() * overWeightPrice;//运费四舍五入
                            freightPrice = freightPrice.add(new BigDecimal(freightDecimal));
                        }
                    }
                    //如果订单总价满足600积分或者88爱币，不作判断（包邮）
                    //else{}
                }
            }
            /*计算订单总运费结束*/

            checkedGoodsPrice = checkedGoodsPrice.add(freightPrice);//商品价格加上邮费
        }
        Map<String, Object> data = new HashMap<>();

        data.put("freightPrice", freightPrice);//邮费
        data.put("deductPrice", checkedGoodsPrice);//商品价格和邮费总和
        return ResponseUtil.ok(data);
    }

    /**
     * 超重价计算
     * @param weight
     * @param overWeightPrice
     * @return
     */
    public double overweightRate(int weight, int overWeightPrice){
        return new BigDecimal((float)(weight-3000)/1000).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()*overWeightPrice;
        //运费四舍五入
    }
}